package org.os.framework.context.interceptor;

import java.util.Optional;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

/**
 * 抽象定义HandlerInterceptor
 * 
 * @author
 */
public interface AbstractHandlerInterceptor extends HandlerInterceptor {

    static final String[] IGNORES = {
            "org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController",
            "springfox.documentation.swagger.web.ApiResourceController"
    };

    /**
     * 忽略拦截
     * 
     * @param request
     * @param response
     * @param handler
     * @return
     */
    public default boolean ignore(HttpServletRequest request, HttpServletResponse response, Object handler) {
        /** 不拦截资源请求 */
        if (handler instanceof ResourceHttpRequestHandler) {
            return true;
        }
        /** 非HandlerMethod不拦截 */
        HandlerMethod method = handler instanceof HandlerMethod ? (HandlerMethod) handler : null;
        if (!Optional.ofNullable(method).isPresent()) {
            return true;
        }
        /** 不拦截指定被忽略的接口 */
        if (null == method || Stream.of(IGNORES).anyMatch(it -> it.equals(method.getBeanType().getName()))) {
            return true;
        }
        return false;
    }

}
